package com.lzx.adx.report.biz;
import cn.hutool.core.io.IoUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Service
public class IpService {

    private Searcher searcher;

    public IpService(){
        // 加载IP数据库
        ClassPathResource resource = new ClassPathResource("data/ip2region.xdb");
        try {
            InputStream inputStream = resource.getInputStream();
            searcher =  Searcher.newWithBuffer(IoUtil.readBytes(inputStream));
        } catch (IOException e) {
            log.error("解析ip地址失败,无法创建搜索器: {}", e);
            throw new RuntimeException(e);
        }
    }

    @SneakyThrows
    public String getRegion(String ip) {
        if(StringUtils.isBlank(ip)){
            return "未知";
        }
        String search = searcher.search(ip);
        return search;
    }
}
